import { message, Button } from 'antd';
import md5 from 'js-md5';

export default {
  namespace: 'auth',
  state: {
    userInfo: null,
  },
  reducers: {
    save(state, { payload }) {
      let newValue = Object.assign({}, state, payload);
      return newValue;
    },
  },
  effects: {
    *login({ payload }, { put, call, select }) {
      const { username, password } = payload;
      const res = yield put.resolve({
        type: '$request/post',
        payload: {
          url: '/api/account/v1/login',
          data: {
            username,
            password: md5(password),
          },
        },
      });
      const { token, privilegeList } = res;
      sessionStorage.setItem('token', token);
      sessionStorage.setItem('privilegeList', JSON.stringify(privilegeList));
      message.success('登录成功！');
      yield put({
        type: '$router/redirect',
        payload: {
          url: '/home',
        },
      });
      yield put({
        type: 'getUserInfo',
      });
    },
    *getUserInfo({ payload }, { put, call, select }) {
      const userInfo = yield put.resolve({
        type: '$request/post',
        payload: {
          url: '/api/account/v1/getUserInfo',
        },
      });
      sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
      yield put({
        type: 'save',
        payload: {
          userInfo,
        },
      });
    },
    *logout({ payload }, { put, call, select }) {
      sessionStorage.removeItem('token');
      yield put.resolve({
        type: '$router/forward',
        payload: {
          url: 'login',
        },
      });
    },

    *changePassword({ payload }, { call, put, select }) {
      let { userInfo } = yield select(s => s.auth);
      if (!userInfo) userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
      const params = {
        uuid: userInfo.uuid,
        oldPassword: md5(payload.currentPassword),
        newPassword: md5(payload.newPassword),
      };
      const res = yield put.resolve({
        type: '$request/post',
        payload: {
          url: '/api/account/v1/updatePassword',
          data: params,
        },
      });
      yield put({
        type: '$msg/showToast',
        payload: {
          title: '密码修改成功，请重新登录！',
          type: 'success',
        },
      });
      yield put({
        type: 'logout',
      });
    },
  },
};
